import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, FileSearchOutlined } from '@ant-design/icons';
import {
  Button,
  message,
  Space,
  Tag,
  Popconfirm,
  Table,
  Select,
  Breadcrumb,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history, useRequest } from 'umi';
import {
  ModalForm,
  ProForm,
  ProFormText,
  ProFormInstance,
  ActionType,
  ProTable,
} from '@ant-design/pro-components';
import ReturnTablist from '@/components/TabList';
import { useBoolean } from 'ahooks';
import moment from 'moment';
import TabBarExtraButton from '@/pages/LabAchievements/ScientificResearch/component/commons/TabBarExtraButton';
import ImportExcel from '@/pages/LabManage/component/ImportExcel';

const { Option } = Select;
export default () => {
  const actionRef = useRef<ActionType>();
  const [tabKey, setTabKey] = useState('个人视角');
  const ref = useRef<ProFormInstance>();

  const [group, setGroup] = useState<any>({ data: [] });
  const [direction, setDirection] = useState<any>({ data: [], group: [] });
  const [manager, setManager] = useState<any>({
    data: [],
    group: [],
    direction: [],
  });

  const [allLabel, setAllLabel] = useState([]);
  const [selectRow, { toggle }] = useBoolean(false);

  const updateStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //多重查询
  const findAllInvitationReportByMutilPart = useRequest(
    (data = { auth: 3 }) => {
      return {
        url: 'http://10.1.40.84:9993/invitation/findAllInvitationReportByMutilPart',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data: { ...data, specialType: '大会特邀报告' },
      };
    },
    {
      manual: true,
    },
  );

  //新增
  const addInvitationReport = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/invitation/addInvitationReport',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //删除
  const delInvitationReport = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/invitation/delInvitationReport',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //权限不同的list
  const getUserInfo = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/user/getUserInfo',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //查找所有标签
  const getAllLabel = useRequest(
    (data = null) => {
      return {
        url: 'http://10.1.40.84:9993/getAllLabel',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //根据tabkey和field返回相应的list
  const getList = (tabkey: string, field: string) => {
    switch (tabkey) {
      case '个人视角':
        return [];
        break;
      case '子方向视角':
        return group[field];
        break;
      case '方向视角':
        return direction[field];
        break;
      case '管理员视角':
        return manager[field];
        break;
    }
  };

  useEffect(() => {
    getUserInfo.run().then((data) => {
      if (typeof data === 'object') {
        setGroup(data.res.ROLE_子方向负责人 || { data: [] });
        setDirection(data.res.ROLE_方向负责人 || { data: [], group: [] });
        setManager(
          data.res.ROLE_管理员 || { data: [], group: [], direction: [] },
        );
      } else {
        message.error(data);
      }
    });
    getAllLabel.run().then((data) => {
      setAllLabel(data);
    });

    // findAllInvitationReportByMutilPart.run();
  }, []);

  const authAdapter = (key: any) => {
    let authTemp: any = 0;
    if (key === '个人视角') {
      authTemp = 0;
    }
    if (key === '子方向视角') {
      authTemp = 1;
    }
    if (key === '方向视角') {
      authTemp = 2;
    }
    if (key === '管理员视角') {
      authTemp = 3;
    }
    return authTemp;
  };

  const confirm = (e: any) => {
    delInvitationReport.run({ id: e.id }).then(() => {
      findAllInvitationReportByMutilPart.run({ auth: authAdapter(tabKey) });
      message.success('删除成功');
    });
  };

  const cancel = (e: any) => {
    message.error('已取消');
  };

  const columns: any = [
    {
      title: '序号',
      align: "center",
      key: 'seq',
      dataIndex: 'seq',
      hideInSearch: true,
      hideInTable: localStorage.getItem('identity') !== '管理员',
    },
    {
      title: '年度',
      align: "center",
      key: 'year',
      dataIndex: 'year',
      hideInSearch: localStorage.getItem('identity') !== '管理员',
      hideInTable: localStorage.getItem('identity') !== '管理员',
      valueType: 'dateYear',
      render: (text: any, record: any, index: any) => {
        return record?.year ? moment(record?.year + '').format('YYYY') : null;
      },
      sorter: {
        compare: (a, b) => a.year - b.year,
      },
    },
    {
      title: '报告人',
      align: "center",
      key: 'authors',
      dataIndex: 'authors',
      hideInSearch: true,
    },
    {
      title: '报告名称',
      align: "center",
      key: 'reportName',
      dataIndex: 'reportName',
      copyable: true,
      // ellipsis: true,
      width: '20%',
    },
    // {
    //   title: '报告类型',
    //   key: 'reportType',
    //   dataIndex: 'reportType',
    //   hideInSearch: true,
    // },
    {
      title: '会议名称',
      align: "center",
      key: 'meetName',
      dataIndex: 'meetName',
      copyable: true,
      // ellipsis: true,
      hideInSearch: true,
      width: '20%',
    },
    {
      title: '会议类型',
      align: "center",
      key: 'meetType',
      dataIndex: 'meetType',
      hideInSearch: true,
    },
    {
      title: '标签',
      align: "center",
      dataIndex: 'label',
      key: 'label',
      valueType: 'select',
      hideInTable: true,
      hideInSearch: localStorage.getItem('identity') !== '管理员',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {allLabel?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '标签',
      align: "center",
      key: 'labels',
      dataIndex: 'labels',
      hideInSearch: true,
      hideInTable: localStorage.getItem('identity') !== '管理员',
      render: (_: any, record: any) =>
        record.labels?.length ? (
          <Space>
            {record.labels.map((e: any) => (
              <Tag key={e}>{e}</Tag>
            ))}
          </Space>
        ) : (
          '-'
        ),
    },
    {
      title: '状态',
      align: "center",
      key: 'finalStr',
      dataIndex: 'finalStr',
      hideInSearch: true,
      align: 'center',
      filters: true,
      onFilter: true,
      valueType: 'select',
      valueEnum: {
        未提交: { text: '未提交' },
        待上传文件: {
          text: '待上传文件',
        },
        待用户修改: {
          text: '待用户修改',
        },
        待子方向负责人审核: {
          text: '待子方向负责人审核',
        },
        待子方向负责人确认: {
          text: '待子方向负责人确认',
        },
        待管理员审核: {
          text: '待管理员审核',
        },
      },
    },
    {
      title: '操作',
      align: "center",
      valueType: 'option',
      key: 'option',
      align: 'center',
      render: (_: any, record: any) => {
        let optionName: any = '';
        let singleRefuseShow: boolean = false;
        let singleRefuseDisabled: boolean = true;
        let deleteHidden: boolean = true;
        if (tabKey === '管理员视角') {
          deleteHidden = false;
        } else {
          if (
            record.finalStr === '待子方向负责人审核' ||
            record.finalStr === '未提交' ||
            record.finalStr === '待上传文件'
          ) {
            deleteHidden = false;
          }
        }
        if (tabKey === '管理员视角') {
          if (record.finalStr === '待管理员审核') {
            singleRefuseDisabled = false;
            optionName = '修改';
          } else {
            optionName = '查看';
          }
        } else {
          if (tabKey === '子方向视角') {
            if (record.finalStr === '待子方向负责人审核') {
              optionName = '修改';
              singleRefuseDisabled = false;
            } else if (record.finalStr === '待子方向负责人确认') {
              optionName = '审核';
            } else {
              optionName = '查看';
            }
          }
          if (tabKey === '方向视角') {
            optionName = '查看';
            singleRefuseShow = true;
          }
          if (tabKey === '个人视角') {
            singleRefuseShow = true;
            if (record.finalStr === '未提交') {
              optionName = '继续填写';
            } else if (
              record.finalStr === '待用户修改' ||
              record.finalStr === '待上传文件'
            ) {
              optionName = '修改';
            } else {
              optionName = '查看';
            }
          }
        }

        return (
          <Space>
            <Button
              type="link"
              key="view"
              onClick={() => {
                if (optionName === '修改' || optionName === '继续填写') {
                  localStorage.setItem('isEdit', '修改');
                } else if (optionName === '审核') {
                  localStorage.setItem('isEdit', '审核');
                } else {
                  localStorage.setItem('isEdit', '查看');
                }
                history.push(
                  '/LabAchievements/CooperationExchange/InvitedReport/Detail/' +
                    record.id,
                );
              }}
            >
              {optionName}
            </Button>
            <Button
              type="link"
              key="agree"
              size="small"
              hidden={singleRefuseShow}
              disabled={singleRefuseDisabled}
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'INVITATION_REPORT',
                    ids: [record.id],
                    status: 2, //审核通过
                    tab: tabKey,
                  })
                  .then(() => {
                    message.success('操作成功');
                    findAllInvitationReportByMutilPart.run({
                      auth: authAdapter(tabKey),
                    });
                  });
              }}
            >
              同意
            </Button>
            <ModalForm
              title="拒绝"
              trigger={
                <Button
                  type="link"
                  hidden={singleRefuseShow}
                  disabled={singleRefuseDisabled}
                  size="small"
                >
                  拒绝
                </Button>
              }
              autoFocusFirstInput
              modalProps={{
                onCancel: () => console.log('run'),
                destroyOnClose: true,
              }}
              submitTimeout={2000}
              onFinish={async (values) => {
                console.log(values);
                updateStatus
                  .run({
                    tableName: 'INVITATION_REPORT',
                    ids: [record.id],
                    status: 3, //拒绝
                    message: values.message,
                    tab: tabKey,
                  })
                  .then(() => {
                    message.success('操作成功');
                    findAllInvitationReportByMutilPart.run({
                      auth: authAdapter(tabKey),
                    });
                  });
                return true;
              }}
              grid={true}
              initialValues={{ message: record.message }}
            >
              <ProForm.Group>
                <ProFormText
                  name="message"
                  label="拒绝原因"
                  placeholder="请输入拒绝原因"
                  colProps={{ span: 24 }}
                  rules={[{ required: true, message: '请输入拒绝原因' }]}
                />
              </ProForm.Group>
            </ModalForm>
            <Popconfirm
              key={'2'}
              title="确定删除吗？"
              onConfirm={() => confirm(record)}
              onCancel={() => cancel}
              okText="确定"
              cancelText="取消"
            >
              {/* <a href="#">删除</a> */}
              <Button disabled={deleteHidden} type="link" size="small">
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
    {
      title: '报告人',
      align: "center",
      key: 'userId',
      dataIndex: 'userId',
      hideInTable: true,
      hideInSearch: tabKey === '个人视角',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {getList(tabKey, 'data')?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '子方向',
      align: "center",
      dataIndex: 'groupId',
      key: 'groupId',
      hideInTable: true,
      hideInSearch: tabKey === '个人视角' || tabKey === '子方向视角',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {getList(tabKey, 'group')?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '方向',
      align: "center",
      dataIndex: 'directionId',
      key: 'directionId',
      hideInTable: true,
      hideInSearch: tabKey !== '管理员视角',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {getList(tabKey, 'direction')?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
  ];

  const Refresh = () => {
    findAllInvitationReportByMutilPart.run({
      auth: authAdapter(tabKey),
      specialType: '大会特邀报告',
    });
  };
  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>合作交流</Breadcrumb.Item>
            <Breadcrumb.Item>大会特邀报告</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      tabList={ReturnTablist()}
      onTabChange={(key: any) => {
        setTabKey(key);
        findAllInvitationReportByMutilPart.run({ auth: authAdapter(key) });
        ref.current?.resetFields();
      }}
    >
      <ProTable
        actionRef={actionRef}
        search={{ labelWidth: 'auto' }}
        formRef={ref}
        columns={columns}
        dataSource={findAllInvitationReportByMutilPart?.data}
        request={async (params) => {
          var temp: any = [];
          await findAllInvitationReportByMutilPart
            .run({ ...params, auth: authAdapter(tabKey) })
            .then((data) => {
              temp = data;
            });
          return {
            data: temp,
            success: true,
          };
        }}
        pagination={{
          pageSize: 10,
        }}
        rowKey="id"
        headerTitle="大会特邀报告列表"
        toolBarRender={() => [
          <TabBarExtraButton
            tableName={'INVITATION_REPORT'}
            url={
              'http://10.1.40.84:9993/invitation/findAllInvitationReportByMutilPart'
            }
            params={{
              auth: authAdapter(tabKey),
              specialType: '大会特邀报告',
            }}
          />,
          <div>
            {tabKey === '管理员视角' || tabKey === '子方向视角' ? (
              <Button
                type="primary"
                icon={<FileSearchOutlined />}
                onClick={() => {
                  toggle();
                }}
              >
                批量审核
              </Button>
            ) : null}
          </div>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              localStorage.setItem('isEdit', '修改');
              history.push(
                '/LabAchievements/CooperationExchange/InvitedReport/Detail/new',
              );
            }}
          >
            新建
          </Button>,
        ]}
        rowSelection={
          selectRow
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                getCheckboxProps: (record) => {
                  let selectRowTag: boolean = true;
                  if (tabKey === '子方向视角') {
                    if (record.finalStr === '待子方向负责人审核') {
                      selectRowTag = false;
                    }
                  }
                  if (tabKey === '管理员视角') {
                    if (record.finalStr === '待管理员审核') {
                      selectRowTag = false;
                    }
                  }
                  return { disabled: selectRowTag };
                },
              }
            : false
        }
        tableAlertOptionRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={16}>
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'INVITATION_REPORT',
                    ids: selectedRowKeys,
                    status: 2, //审核通过
                    tab: tabKey,
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllInvitationReportByMutilPart.run({
                      auth: authAdapter(tabKey),
                    });
                  });
              }}
            >
              审核通过
            </a>
          </Space>
        )}
      />
    </PageContainer>
  );
};
